package cn.iocoder.yudao.module.wine.service.supplymarket;

import cn.hutool.core.collection.CollectionUtil;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.module.system.api.dict.DictDataApi;
import cn.iocoder.yudao.module.system.api.dict.dto.DictDataRespDTO;
import cn.iocoder.yudao.module.wine.controller.admin.countnameconfig.vo.CountNameConfigRespVO;
import cn.iocoder.yudao.module.wine.controller.app.supplymarket.vo.AppSupplyMarketPageReqVO;
import cn.iocoder.yudao.module.wine.dal.dataobject.countnameconfig.CountNameConfigDO;
import cn.iocoder.yudao.module.wine.dal.mysql.countnameconfig.CountNameConfigMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import org.springframework.validation.annotation.Validated;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

import cn.iocoder.yudao.module.wine.controller.admin.supplymarket.vo.*;
import cn.iocoder.yudao.module.wine.dal.dataobject.supplymarket.SupplyMarketDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.wine.dal.mysql.supplymarket.SupplyMarketMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.wine.enums.ErrorCodeConstants.*;

/**
 * 酒类行情管理 Service 实现类
 *
 * @author 管理员
 */
@Service
@Validated
@Slf4j
public class SupplyMarketServiceImpl implements SupplyMarketService {

    @Resource
    private SupplyMarketMapper supplyMarketMapper;

    @Resource
    private CountNameConfigMapper countNameConfigMapper;

    @Resource
    private DictDataApi dataApi;


    @Override
    public Integer createSupplyMarket(SupplyMarketSaveReqVO createReqVO) {
        // 插入
        SupplyMarketDO supplyMarket = BeanUtils.toBean(createReqVO, SupplyMarketDO.class);
        supplyMarketMapper.insert(supplyMarket);
        // 返回
        return supplyMarket.getId();
    }

    @Override
    public void updateSupplyMarket(SupplyMarketSaveReqVO updateReqVO) {
        // 校验存在
        validateSupplyMarketExists(updateReqVO.getId());
        // 更新
        SupplyMarketDO updateObj = BeanUtils.toBean(updateReqVO, SupplyMarketDO.class);
        supplyMarketMapper.updateById(updateObj);
    }

    @Override
    public void deleteSupplyMarket(Integer id) {
        // 校验存在
        validateSupplyMarketExists(id);
        // 删除
        supplyMarketMapper.deleteById(id);
    }

    @Override
    public void deleteSupplyMarketList(SupplyMarketDelVO reqVO) {

        // 删除
        supplyMarketMapper.delete(new LambdaQueryWrapper<SupplyMarketDO>()
                .between(SupplyMarketDO::getCountTime, reqVO.getStartTime(),reqVO.getEndTime()));

    }


    private void validateSupplyMarketExists(Integer id) {
        if (supplyMarketMapper.selectById(id) == null) {
            throw exception(INFO_NOT_EXISTS);
        }
    }

    @Override
    public SupplyMarketDO getSupplyMarket(Integer id) {
        return supplyMarketMapper.selectById(id);
    }

    @Override
    public PageResult<SupplyMarketDO> getSupplyMarketPage(SupplyMarketPageReqVO pageReqVO) {
        return supplyMarketMapper.selectPage(pageReqVO);
    }

    @Override
    public List<SupplyMarketDO> appGetSupplyMarketList(AppSupplyMarketPageReqVO reqVO) {
        return supplyMarketMapper.getSupplyMarketList(reqVO);
    }

    @Override
    public List<SupplyMarketDO> getSupplyMarketListByConfig(AppSupplyMarketPageReqVO reqVO) {
        if (reqVO.getSupplyTypeId() == null) {
            PageResult<CountNameConfigDO> countNameConfigDOPageResult = countNameConfigMapper.selectByPage(reqVO);
            List<CountNameConfigDO> countNameConfigDOS = countNameConfigDOPageResult.getList();
            if (CollectionUtil.isEmpty(countNameConfigDOS)) {
                return null;
            }
            List<SupplyMarketDO> list = new ArrayList<>();

            countNameConfigDOS.forEach(item -> {
                log.info("看看配置数据:{}",item);
                SupplyMarketDO supplyMarketDO = supplyMarketMapper.selectOne(new LambdaQueryWrapperX<SupplyMarketDO>()
                        .eq(SupplyMarketDO::getFragranceType, item.getFragranceType())
                        .eq(SupplyMarketDO::getShowYear, item.getShowYear())
                        .eq(SupplyMarketDO::getPacking, item.getPacking())
                        .eq(SupplyMarketDO::getSupplyTypeId, item.getSupplyTypeId())
                        .eq(SupplyMarketDO::getInfoTitle, item.getCountName())
                        .orderByDesc(SupplyMarketDO::getCreateTime)
                        .last("limit 1 ")
                );
                log.info("看看行情数据:{}",supplyMarketDO);
                if (supplyMarketDO != null) {
                    list.add(supplyMarketDO);
                } else {
                    SupplyMarketDO supplyMarketDO1 = new SupplyMarketDO();
                    supplyMarketDO1.setId(0);
                    supplyMarketDO1.setInfoTitle(item.getCountName());
                    supplyMarketDO1.setInfoNme(item.getCountName());
                    supplyMarketDO1.setFragranceType(item.getFragranceType());
                    supplyMarketDO1.setShowYear(item.getShowYear());
                    supplyMarketDO1.setPacking(item.getPacking());
                    supplyMarketDO1.setSupplyTypeId(item.getSupplyTypeId());
                    supplyMarketDO1.setSalePrice(new BigDecimal(0));
                    supplyMarketDO1.setStatus(0);
                    supplyMarketDO1.setAveragePrice(new BigDecimal(0));
                    supplyMarketDO1.setCreateTime(LocalDateTime.now());
                    list.add(supplyMarketDO1);
                }
            });
            if (CollectionUtil.isEmpty(list)) {
                return list;
            }
            return list.stream().sorted(Comparator.comparing(SupplyMarketDO::getCreateTime).reversed()).collect(Collectors.toList());

        } else {
            String keywords = reqVO.getKeywords();
            if (!StringUtils.isEmpty(keywords)) {
                String[] split = keywords.split(" ");
                List<SupplyMarketDO> list = new ArrayList<>();
                for (String s : split) {
                    List<SupplyMarketDO> supplyMarketDOS = supplyMarketMapper.selectList(new LambdaQueryWrapperX<SupplyMarketDO>()
                            .eqIfPresent(SupplyMarketDO::getFragranceType, reqVO.getFragranceType())
                            .eqIfPresent(SupplyMarketDO::getSupplyTypeId, reqVO.getSupplyTypeId())
                            .eqIfPresent(SupplyMarketDO::getInfoType, reqVO.getInfoType())
                            .orderByDesc(SupplyMarketDO::getCreateTime)
                            .likeIfPresent(SupplyMarketDO::getInfoNme, s)
                            .likeIfPresent(SupplyMarketDO::getInfoTitle, s)

                    );
                    list.addAll(supplyMarketDOS);
                }
                if (!CollectionUtil.isEmpty(list)) {
                    return list.stream().distinct().collect(Collectors.toList());
                }
                return list;
            }
            return supplyMarketMapper.selectList(new LambdaQueryWrapperX<SupplyMarketDO>()
                    .eqIfPresent(SupplyMarketDO::getFragranceType, reqVO.getFragranceType())
                    .eqIfPresent(SupplyMarketDO::getPacking, reqVO.getPacking())
                    .eqIfPresent(SupplyMarketDO::getSupplyTypeId, reqVO.getSupplyTypeId())
                    .orderByDesc(SupplyMarketDO::getCreateTime)
            );
        }
    }

    @Override
    public PageResult<CountNameConfigRespVO> getMarketConfigList(AppSupplyMarketPageReqVO reqVO) {
        PageResult<CountNameConfigRespVO> countNameConfigRespVOPageResult = countNameConfigMapper.selectConfigByPage(reqVO);
        if (countNameConfigRespVOPageResult != null) {
            List<CountNameConfigRespVO> list = countNameConfigRespVOPageResult.getList();

            List<DictDataRespDTO> packing = dataApi.getDictDataList("packing");
            List<DictDataRespDTO> year = dataApi.getDictDataList("year");

            List<CountNameConfigRespVO> collect = list.stream().map(item -> {
                String countName = item.getCountName();
                SupplyMarketDO supplyMarketDO = supplyMarketMapper.selectOne(new LambdaQueryWrapperX<SupplyMarketDO>()
                        .eq(SupplyMarketDO::getInfoNme, countName)
                        .eq(SupplyMarketDO::getShowYear, item.getShowYear())
                        .eq(SupplyMarketDO::getPacking, item.getPacking())
                        .orderByDesc(SupplyMarketDO::getCreateTime)
                        .last("limit 1"));

                //字典值转成字典名称
                for (DictDataRespDTO dictDataRespDTO : packing) {
                    if (dictDataRespDTO.getValue().equals(String.valueOf(item.getPacking()))) {
                        item.setPackingName(dictDataRespDTO.getLabel());
                        break;
                    }
                }
                for (DictDataRespDTO dictDataRespDTO : year) {
                    if (dictDataRespDTO.getValue().equals(String.valueOf(item.getShowYear()))) {
                        item.setShowYearName(dictDataRespDTO.getLabel());
                        break;
                    }
                };
                item.setAveragePrice(BigDecimal.ZERO);
                item.setSalePrice(BigDecimal.ZERO);
                if (supplyMarketDO != null) {
                    item.setAveragePrice(supplyMarketDO.getAveragePrice());
                    item.setSalePrice(supplyMarketDO.getSalePrice());
                    item.setStatus(supplyMarketDO.getStatus());
                }
                return item;
            }).collect(Collectors.toList());
            countNameConfigRespVOPageResult.setList(collect);
        }
        return countNameConfigRespVOPageResult;
    }

    @Override
    public List<SupplyMarketDO> getSupplyMarketByDay(CountNameConfigDO countNameConfigDO) {
        // 获取今天的日期
        // 获取当前的日期时间
        LocalDateTime now = LocalDateTime.now();

        // 设置时间为今天的 0 时 0 分 0 秒
        LocalDateTime todayStart = LocalDateTime.of(now.toLocalDate(), LocalTime.of(0, 0, 0));

        // 将今天的日期和0点时间组合
        LocalDateTime dateTime = todayStart.minusDays(1L);
        String countName = countNameConfigDO.getCountName();
        return supplyMarketMapper.selectList(new LambdaQueryWrapperX<SupplyMarketDO>()
                .eqIfPresent(SupplyMarketDO::getSupplyTypeId, countNameConfigDO.getSupplyTypeId())
                .eqIfPresent(SupplyMarketDO::getFragranceType, countNameConfigDO.getFragranceType())
                .eqIfPresent(SupplyMarketDO::getShowYear, countNameConfigDO.getShowYear())
                .eqIfPresent(SupplyMarketDO::getPacking, countNameConfigDO.getPacking())
                .eqIfPresent(SupplyMarketDO::getInfoNme, countName)
                .le(SupplyMarketDO::getCreateTime,todayStart)
                .ge(SupplyMarketDO::getCreateTime, dateTime)
                .orderByDesc(SupplyMarketDO::getCreateTime));
    }
}
